package com.csi.service.impl;

import com.csi.domain.UserBook;
import com.csi.mapper.OrderMapper;
import com.csi.mapper.TravelMapper;
import com.csi.service.OrderService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.*;

@Service
public class OrderServiceImpl implements OrderService {

    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(100);
    private ConcurrentHashMap<Long, ScheduledFuture<?>> scheduledFutures = new ConcurrentHashMap<>();

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private TravelMapper travelMapper;

    @Override
    public Map<String, Object> findById(long userId, String orderStatus) {
        return orderMapper.findById(userId,orderStatus);
    }

    /**
     * 预定订单
     * @param userBook
     * @return
     */
    @Override
    @Transactional
    public int bookOrder(UserBook userBook) {
        int updated = travelMapper.updated(userBook.getPeopleNum(),userBook.getTravelPackageId());
        int saved = orderMapper.save(userBook);

        scheduleUnlockTask(userBook);
        return (updated+saved) > 0 ? (int) userBook.getId() : 0;
    }

    /**
     * 支付订单
     * @param payId
     * @return
     */
    @Transactional
    @Override
    public int updatedPayOrder(long payId) {
        int updated =  orderMapper.updatedPayOrder(payId);
        scheduledFutures.remove(payId); //将其删除掉
        return updated;
    }


    /**
     * 完成订单
     * @param payId
     * @return
     */
    @Override
    public int updatedFinishOrder(long payId) {
        return orderMapper.updatedFinishOrder(payId);
    }


    @Transactional
    public void scheduleUnlockTask(UserBook userBook){
        long delay = 30*60*1000;
        ScheduledFuture<?> future = scheduler.schedule(() ->{
            String payStatus = orderMapper.findPayStatusById(userBook.getId());
            if ("待支付".equals(payStatus)){
                int updated2 = orderMapper.updateCancel(userBook.getId());
                int updated3 = travelMapper.updatedCancel(userBook.getPeopleNum(),userBook.getTravelPackageId());
            }
        },delay,TimeUnit.MILLISECONDS);
        scheduledFutures.put(userBook.getId(),future);
    }
}
